import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken())
  const name = ref('')
  const avatar = ref('')
  const roles = ref([])
  const permissions = ref([])

  // 登录
  async function loginAction(userInfo) {
    const { username, password } = userInfo
    try {
      const response = await login({ username: username.trim(), password })
      const { data } = response
      token.value = data.token
      setToken(data.token)
      await getInfoAction()
      router.push('/dashboard')
      return Promise.resolve()
    } catch (error) {
      console.error('Login failed:', error)
      resetToken()
      throw error
    }
  }

  // 获取用户信息
  async function getInfoAction() {
    try {
      const response = await getUserInfo()
      const { data } = response
      if (!data) {
        return Promise.reject('验证失败，请重新登录')
      }
      const { roles: userRoles, name: userName, avatar: userAvatar, permissions: userPermissions } = data
      if (!userRoles || userRoles.length <= 0) {
        return Promise.reject('用户角色必须是非空数组!')
      }
      roles.value = userRoles
      name.value = userName
      avatar.value = userAvatar
      permissions.value = userPermissions || []
      return Promise.resolve(data)
    } catch (error) {
      console.error('获取用户信息出错:', error)
      resetToken()
      throw error
    }
  }

  // 登出
  async function logoutAction() {
    try {
      await logout()
      token.value = ''
      roles.value = []
      permissions.value = []
      removeToken()
      router.push('/login')
      return Promise.resolve()
    } catch (error) {
      console.error('Logout failed:', error)
      throw error
    }
  }

  // 重置 token
  function resetToken() {
    token.value = ''
    roles.value = []
    permissions.value = []
    removeToken()
  }

  function hasRole(role) {
    return roles.value.includes(role)
  }

  /**
   * 检查是否有权限
   */
  const hasPermission = (permission) => {
    if (!permission) return true
    
    // 直接使用store中的状态，而不是重新获取store
    const userPermissions = permissions.value || []
    const userRoles = roles.value || []
    
    console.log('检查权限:', permission)
    console.log('用户角色:', userRoles)
    console.log('用户权限:', userPermissions)
    
    // 如果是管理员，直接返回true
    if (userRoles.includes('ROLE_ADMIN')) {
      console.log('用户是管理员，允许访问')
      return true
    }
    
    // 检查完整权限
    if (userPermissions.includes(permission)) {
      console.log('找到完整权限匹配')
      return true
    }
    
    // 检查前缀权限
    const hasPrefixPermission = userPermissions.some(p => {
      const result = permission.startsWith(p + ':')
      if (result) {
        console.log('找到前缀权限匹配:', p)
      }
      return result
    })
    
    if (hasPrefixPermission) {
      return true
    }
    
    console.log('没有找到匹配的权限')
    return false
  }

  return {
    token,
    name,
    avatar,
    roles,
    permissions,
    loginAction,
    getInfoAction,
    logoutAction,
    resetToken,
    hasRole,
    hasPermission
  }
}) 